package com.firefly.web.controller.api.login;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import com.firefly.util.handle.FireflyException;
import com.firefly.web.controller.api.ApiRestController;
import com.firefly.dao.dto.login.WechatCodeDto;
import com.firefly.dao.dto.login.WechatPhoneDto;
import com.firefly.dao.vo.login.WechatCodeVo;
import com.firefly.dao.vo.mc.McLoginVo;
import com.firefly.service.command.mc.McUserCommand;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;

/**
 * @description:
 * @author: lzg(萤火科技 ： 854378082 @ qq.com)
 * @date: 2023/2/8
 **/
@Slf4j
@ApiRestController("wechat")
public class WechatLoginController {
    private final WxMaService wxMaService;
    private final McUserCommand mcUserCommand;
    @Autowired
    public WechatLoginController(WxMaService wxMaService,McUserCommand mcUserCommand){
        this.wxMaService = wxMaService;
        this.mcUserCommand = mcUserCommand;
    }
    // code换取openId与sessionKey
    @PostMapping("code")
    public WechatCodeVo postCode(@Validated WechatCodeDto request){
        String code = request.getCode();
        WechatCodeVo result = new WechatCodeVo();
        try {
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
            result.setOpenId(session.getOpenid());
            result.setSessionKey(session.getSessionKey());
            return result;
        } catch (WxErrorException e) {
            log.error(e.getMessage(),e);
            throw new FireflyException(500,e.toString());
        } finally {
            WxMaConfigHolder.remove();//清理ThreadLocal
        }
    }
    // 授权手机号登录或者注册
    @PostMapping("phone")
    public McLoginVo postPhone(@Validated WechatPhoneDto request) throws Exception {
        WxMaPhoneNumberInfo session = wxMaService.getUserService().getPhoneNoInfo(request.sessionKey,request.encryptedData,request.iv);
        String phone = session.getPhoneNumber();
        WxMaConfigHolder.remove();//清理ThreadLocal
        McLoginVo result = mcUserCommand.loginOrRegister(phone,request.openId);
        return result;
    }
}
